package controllers.api;

import play.libs.MimeTypes;
import play.mvc.Controller;
import play.server.ServletWrapper;
import utils.files.GAEFileService;
import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileReadChannel;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.LockException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.Channels;
import javax.servlet.http.HttpServletResponse;

public class Files extends MeApi {
	
	public static void serve(String key) throws LockException, IOException {
		BlobInfoFactory infoFactory = new BlobInfoFactory();
		BlobKey blobKey = new BlobKey(key);
		BlobInfo blobInfo = infoFactory.loadBlobInfo(blobKey);
		if(blobInfo==null) notFound();
		response.setContentTypeIfNotSet(blobInfo.getContentType());
		FileService fileService = FileServiceFactory.getFileService();
		AppEngineFile file = fileService.getBlobFile(blobKey);
		boolean lock = false;
		FileReadChannel readChannel = fileService.openReadChannel(file, lock);
		InputStream inputStream = Channels.newInputStream(readChannel);
		renderBinary(inputStream);
	}
	
}